﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using SurveySez.ViewModel.Editor;
using UpdateControls.XAML;

namespace SurveySez.View
{
	public partial class PrivateWindow : Window
	{
		private DispatcherTimer _timer;
        public PrivateWindow()
		{
			this.InitializeComponent();

			InitializeCommitTimer();
		}

		private static List<Key> NumberKeys = new List<Key>() { Key.NumPad1, Key.NumPad2, Key.NumPad3, Key.NumPad4, Key.NumPad5, Key.NumPad6, Key.NumPad7, Key.NumPad8, Key.NumPad9 };

		private void Window_KeyDown(object sender, KeyEventArgs e)
		{
			DashboardViewModel viewModel = ForView.Unwrap<PrivateViewModel>(DataContext).Dashboard;
			if (viewModel != null)
			{
				if (e.Key == Key.Add)
					viewModel.NextRound();
				else if (e.Key == Key.Subtract)
					viewModel.PreviousRound();
				else if (e.Key == Key.NumPad0)
				{
					_timer.Stop();
					viewModel.GuessIncorrect();
					_timer.Start();
				}
				else if (e.Key == Key.Back)
				{
					_timer.Stop();
					viewModel.Abort();
				}

				int guess = NumberKeys.IndexOf(e.Key);
				if (guess >= 0)
				{
					_timer.Stop();
					viewModel.GuessAnswer(guess);
					_timer.Start();
				}
			}
		}

		private void InitializeCommitTimer()
		{
			_timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2.0) };
			_timer.Tick += (a, b) =>
			{
				DashboardViewModel viewModel = ForView.Unwrap<PrivateViewModel>(DataContext).Dashboard;
				if (viewModel != null)
					viewModel.Commit();
				_timer.Stop();
			};
		}
	}
}